可以通过信号和槽机制来实现按钮按下改变颜色的功能。 设置按钮按下的信号:QPushButton::pressed()。创建一个槽函数,用于改变按钮的颜色。将信号和槽函数连接起来:QObject::connect()。在槽函数中设置按钮的颜色,可以使用QPushButton::setStyleSheet()方法来设置样式表。以下是我们写的代码: #include
class ButtonColorChanger : public QWidget
{
public:
ButtonColorChanger(QWidget *parent = nullptr) : QWidget(parent)
{
QPushButton *button = new QPushButton("Press me", this);
connect(button, &QPushButton::pressed, this, &ButtonColorChanger::changeButtonColor);
}
private slots:
void changeButtonColor()
{
QPushButton *button = qobject_cast(sender());
if (button)
button->setStyleSheet("background-color: red");
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ButtonColorChanger w;
w.show();
return a.exec();
}
|